package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.CollectionUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.apkextract.lib.model.AeCollectManager;
import com.stark.apkextract.lib.model.AeExportInfo;
import com.stark.apkextract.lib.model.AeExporter;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SearchApkAdapter;
import flc.ast.bean.ApkBean;
import flc.ast.databinding.ActivityApkExportBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.RxUtil;

public class ApkExportActivity extends BaseAc<ActivityApkExportBinding> {

    private SearchApkAdapter apkAdapter;

    @Override
    protected int onCreate() {
        return R.layout.activity_apk_export;
    }

    @Override
    protected void initView() {
        mDataBinding.ivApkExportBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.rvExportList.setLayoutManager(new LinearLayoutManager(mContext));
        apkAdapter = new SearchApkAdapter();
        mDataBinding.rvExportList.setAdapter(apkAdapter);
        apkAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        ApkBean item = (ApkBean) adapter.getItem(position);
        ApkDetailsActivity.apkBean = item;
        startActivity(ApkDetailsActivity.class);
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        showDialog(getString(com.stark.common.res.R.string.loading));
        RxUtil.create(new RxUtil.Callback<List<ApkBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<ApkBean>> emitter) {
                List<AeExportInfo> listSys = AeExporter.getInstance().getExportInfos();
                List<ApkBean> apkBeans = new ArrayList<>();
                ApkBean bean;
                for (AeExportInfo info : listSys) {
                    bean = new ApkBean();
                    bean.pkgName = info.packageName;
                    apkBeans.add(bean);
                }
                emitter.onNext(apkBeans);
            }

            @Override
            public void accept(List<ApkBean> packageNames) {
                if (!CollectionUtils.isEmpty(packageNames)) {
                    mDataBinding.rvExportList.setVisibility(View.VISIBLE);
                    apkAdapter.setList(packageNames);
                } else {
                    mDataBinding.rvExportList.setVisibility(View.GONE);
                }
                dismissDialog(500L);
            }
        });
    }

}